﻿package com.maxjay.system.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.maxjay.system.bo.UserInfo;

public class LoginFilter extends HttpServlet implements Filter {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	static Logger logger = Logger.getLogger(LoginFilter.class);

	//private FilterConfig filterConfig;

	boolean isFilter = true;

	/**
	 * 过滤的路径
	 */
	static String[] filterPath = { "COMMONSIMPLELIST", "/DBMANAGER/", "/USER/" };

	public void init(FilterConfig filterConfig) throws ServletException {
		//this.filterConfig = filterConfig;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletResponse httpResponse = null;
		HttpServletRequest httpRequest = (HttpServletRequest) request;

		isFilter = false;

		httpResponse = (HttpServletResponse) response;
		UserInfo user = (UserInfo) httpRequest.getSession().getAttribute(UserInfo.SYS_USERINFO);
		String uri = httpRequest.getRequestURI().toUpperCase();
		for (String filter : filterPath) {
			// 判断是否需要过滤
			if (uri.indexOf(filter) != -1) {
				isFilter = true;
				break;
			}
		}
		// 用户没有登陆则转到登陆页面
		if (user == null && isFilter == true) {
			httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.jsp");
		} else {
			filterChain.doFilter(request, response);
		}
	}

	// Clean up resources
	public void destroy() {
	}

}
